from sqlalchemy import Column, Integer, BigInteger, String, DateTime, TIMESTAMP, CHAR, Text, SmallInteger
from sqlalchemy.sql import func
from src.database.base import Base
from typing import Optional
from datetime import datetime, timezone, timedelta
import config


def get_china_time():
    """获取东八区当前时间"""
    china_tz = timezone(timedelta(hours=8))
    return datetime.now(china_tz)


class UserInfo(Base):
    """会员表模型"""
    __tablename__ = "user_info"
    __table_args__ = {
        'comment': '会员表',
        'mysql_engine': 'InnoDB',
        'mysql_charset': 'utf8mb4',
        'mysql_collate': 'utf8mb4_0900_ai_ci',
        'mysql_row_format': 'DYNAMIC'
    }

    # 主键ID - 根据数据库类型选择合适的整数类型
    if getattr(config, 'DATABASE_TYPE', 'sqlite') == 'sqlite':
        id = Column(
            Integer,
            primary_key=True,
            autoincrement=True,
            comment='id'
        )
    else:
        id = Column(
            BigInteger,
            primary_key=True,
            autoincrement=True,
            comment='id'
        )
    
    # 用户基本信息
    username = Column(
        String(50),
        nullable=True,
        comment='用户名'
    )
    
    password = Column(
        String(500),
        nullable=True,
        comment='密码'
    )
    
    nick_name = Column(
        String(100),
        nullable=True,
        comment='昵称'
    )
    
    phone = Column(
        String(17),
        nullable=True,
        comment='电话号码'
    )
    
    email = Column(
        String(100),
        nullable=True,
        comment='邮箱'
    )
    
    avatar = Column(
        String(200),
        nullable=True,
        comment='头像'
    )
    
    sex = Column(
        SmallInteger,
        nullable=True,
        comment='性别'
    )
    
    # 微信相关
    open_id = Column(
        String(45),
        nullable=True,
        comment='微信open id'
    )
    
    union_id = Column(
        String(45),
        nullable=True,
        comment='微信开放平台unionID'
    )
    
    # 登录信息
    last_login_ip = Column(
        String(50),
        nullable=True,
        comment='最后一次登录ip'
    )
    
    last_login_time = Column(
        DateTime,
        nullable=True,
        comment='最后一次登录时间'
    )
    
    # 状态信息
    status = Column(
        SmallInteger,
        nullable=True,
        default=1,
        comment='状态：1为正常，0为禁止'
    )
    
    # 审计字段
    create_time = Column(
        TIMESTAMP,
        nullable=False,
        server_default=func.current_timestamp(),
        comment='创建时间'
    )
    
    create_by = Column(
        BigInteger,
        nullable=True
    )
    
    update_time = Column(
        TIMESTAMP,
        nullable=False,
        server_default=func.current_timestamp(),
        onupdate=func.current_timestamp(),
        comment='更新时间'
    )
    
    update_by = Column(
        BigInteger,
        nullable=True,
        comment='更新者'
    )
    
    del_flag = Column(
        CHAR(1),
        nullable=False,
        default='0',
        comment='删除标志（0代表存在 2代表删除）'
    )
    
    remark = Column(
        String(255),
        nullable=True,
        comment='备注'
    )

    def __repr__(self):
        return f"<UserInfo(id={self.id}, username='{self.username}', nick_name='{self.nick_name}')>"
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'username': self.username,
            'nick_name': self.nick_name,
            'phone': self.phone,
            'email': self.email,
            'avatar': self.avatar,
            'sex': self.sex,
            'open_id': self.open_id,
            'union_id': self.union_id,
            'last_login_ip': self.last_login_ip,
            'last_login_time': self.last_login_time.isoformat() if self.last_login_time else None,
            'status': self.status,
            'create_time': self.create_time.isoformat() if self.create_time else None,
            'create_by': self.create_by,
            'update_time': self.update_time.isoformat() if self.update_time else None,
            'update_by': self.update_by,
            'del_flag': self.del_flag,
            'remark': self.remark
        } 